package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.HmzWarehouseMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.HmzProductMapper;

/**
 * 用于存储产品信息的Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-10
 */
@Service
public class HmzProductServiceImpl implements IHmzProductService
{
    @Autowired
    private HmzProductMapper hmzProductMapper;
    @Autowired
    private HmzWarehouseMapper hmzWarehouseMapper;
    @Autowired
    private IHmzProductTypeService hmzProductTypeService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IHmzEraService hmzEraService;
    @Autowired
    private IHmzCompletenessService hmzCompletenessService;
    @Autowired
    private IHmzCollectionSourceService hmzCollectionSourceService;
    @Autowired
    private IHmzCollectionLevelService hmzCollectionLevelService;


    /**
     * 查询用于存储产品信息的
     *
     * @param id 用于存储产品信息的主键
     * @return 用于存储产品信息的
     */
    @Override
    public HmzProduct selectHmzProductById(Long id)
    {
        HmzProduct hmzProduct = hmzProductMapper.selectHmzProductById(id);
        if(StringUtils.isNotNull(hmzProduct)){
            HmzWarehouse hmzWarehouse = hmzWarehouseMapper.selectHmzWarehouseById(hmzProduct.getWarehouseId());
            String createBy = hmzProduct.getCreateBy();
            String approver = hmzProduct.getApprover();
            if(!"".equals(createBy) &&  null !=createBy){
                if(!"".equals(approver) && null !=approver){
                    SysUser sysUser1 = userService.selectUserById(Long.valueOf(approver));
                    hmzProduct.setApproverName(sysUser1.getUserName());
                }
                SysUser sysUser1 = userService.selectUserById(Long.valueOf(approver));
                hmzProduct.setApproverName(sysUser1.getUserName());
                SysUser sysUser = userService.selectUserById(Long.valueOf(createBy));
                hmzProduct.setCreateByName(sysUser.getUserName());
            }
            if(StringUtils.isNotNull(hmzWarehouse)){
                hmzProduct.setWarehouseIdNmae(hmzWarehouse.getWarehouseName());
            }
        }

        return hmzProduct;
    }

    /**
     * 查询用于存储产品信息的列表
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 用于存储产品信息的
     */
    @Override
    public List<HmzProduct> selectHmzProductList(HmzProduct hmzProduct)

    {
        List<HmzProduct> hmzProducts = hmzProductMapper.selectHmzProductList(hmzProduct);
        for (HmzProduct product : hmzProducts) {
            String createBy = product.getCreateBy();
            if(!"".equals(createBy) &&  null !=createBy){
                SysUser sysUser = userService.selectUserById(Long.valueOf(createBy));
                product.setCreateByName(sysUser.getUserName());
                String approver = product.getApprover();
                if(!"".equals(approver) && null !=approver){
                    SysUser sysUser1 = userService.selectUserById(Long.valueOf(approver));
                    product.setApproverName(sysUser1.getUserName());
                }

            }
            Long warehouseId = product.getWarehouseId();
            HmzWarehouse hmzWarehouse = hmzWarehouseMapper.selectHmzWarehouseById(warehouseId);
            HmzProductType hmzProductType = hmzProductTypeService.selectHmzProductTypeById(product.getProductTypeId());
            if(StringUtils.isNotNull(hmzWarehouse)){
                product.setWarehouseIdNmae(hmzWarehouse.getWarehouseName());
            }
            if(StringUtils.isNotNull(hmzProductType)){
                product.setProductTypeIdName(hmzProductType.getProductTypeName());
            }


        }
        return hmzProducts;
    }

    /**
     * 新增用于存储产品信息的
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 结果
     */
    @Override
    public int insertHmzProduct(HmzProduct hmzProduct)
    {
        hmzProduct.setCreateTime(DateUtils.getNowDate());
        hmzProduct.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        return hmzProductMapper.insertHmzProduct(hmzProduct);
    }

    /**
     * 修改用于存储产品信息的
     *
     * @param hmzProduct 用于存储产品信息的
     * @return 结果
     */
    @Override
    public int updateHmzProduct(HmzProduct hmzProduct)
    {
        hmzProduct.setUpdateTime(DateUtils.getNowDate());
        int isApprover = hmzProduct.getIsApprover();
        if(isApprover == 1){
            hmzProduct.setApprover(String.valueOf(SecurityUtils.getUserId()));
        }
        return hmzProductMapper.updateHmzProduct(hmzProduct);
    }

    /**
     * 批量删除用于存储产品信息的
     *
     * @param ids 需要删除的用于存储产品信息的主键
     * @return 结果
     */
    @Override
    public int deleteHmzProductByIds(Long[] ids)
    {
        return hmzProductMapper.deleteHmzProductByIds(ids);
    }

    /**
     * 删除用于存储产品信息的信息
     *
     * @param id 用于存储产品信息的主键
     * @return 结果
     */
    @Override
    public int deleteHmzProductById(Long id)
    {
        return hmzProductMapper.deleteHmzProductById(id);
    }

    @Override
    public String importUser(List<HmzProduct> stuList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(stuList) || stuList.size() == 0)
        {
            throw new ServiceException("导入基本信息数据不能为空！");
        }
        Long rfidcode= 0L;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        List<String> list =new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format1 = format.format(new Date());
        String s = format1.replaceAll("-", "");
        String s1 = s.replaceAll(" ", "");
        String s2 = s1.replaceAll(":", "");
        rfidcode = Long.valueOf(s2);
        for (HmzProduct stu : stuList)
        {

            try {
//                String l = String.valueOf(System.currentTimeMillis()/1000);
//                // 获取当前时间
//                LocalDateTime now = LocalDateTime.now();
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
//                String timestamp = now.format(formatter);
//                // rfidcode++;
////                String serialNumber = UniqueSerialNumberGenerator.generateSerialNumber();
//                String serialNumber = UniqueIdGenerator.generateUniqueId();
////                String serialNumber = UniqueIdGenerator.getTimeSerialNoStr();
//                System.err.println(serialNumber);
//                stu.setRfidCode(serialNumber);
                successNum++;
//                stu.setCreateBy(operName);
//                stu.setQuantityResidue(stu.getQuantity());
                //分类号查询
                String productTypeIdName = stu.getProductTypeIdName();
                if(!"".equals(productTypeIdName) && null!=productTypeIdName){
                    HmzProductType hmzProductType = new HmzProductType();
                    hmzProductType.setProductTypeName(productTypeIdName);
                    List<HmzProductType> hmzProductTypes = hmzProductTypeService.selectHmzProductTypeList(hmzProductType);
                    if(hmzProductTypes !=null && hmzProductTypes.size() > 0){
                        Long id = hmzProductTypes.get(0).getId();
                        stu.setProductTypeId(id);
                    }
                }

                //方位查询
                Long warehouseId = stu.getWarehouseId();
                if(null != warehouseId){

                }
                //年代
                String era = stu.getEra();
                if(!"".equals(era) && null!=era){
                    HmzEra hmzEra = new HmzEra();
                    hmzEra.setEra(era);
                    List<HmzEra> hmzEras = hmzEraService.selectHmzEraList(hmzEra);
                    if(hmzEras !=null && hmzEras.size() > 0){
                        stu.setEra(String.valueOf(hmzEras.get(0).getId()));
                    }
                }
                //完残程度
                String completeness = stu.getCompleteness();
                if(!"".equals(completeness) && null!=completeness){
                    HmzCompleteness hmzCompleteness = new HmzCompleteness();
                    hmzCompleteness.setCompleteness(completeness);
                    List<HmzCompleteness> hmzCompletenesses = hmzCompletenessService.selectHmzCompletenessList(hmzCompleteness);
                    if(hmzCompletenesses !=null && hmzCompletenesses.size() > 0){
                        stu.setCompleteness(String.valueOf(hmzCompletenesses.get(0).getId()));
                    }
                }
                //藏品级别
                String collectionLevel = stu.getCollectionLevel();
                if(!"".equals(collectionLevel) && null!=collectionLevel){
                    HmzCollectionLevel hmzCollectionLevel = new HmzCollectionLevel();
                    hmzCollectionLevel.setCollectionLevel(collectionLevel);
                    List<HmzCollectionLevel> hmzCollectionLevels = hmzCollectionLevelService.selectHmzCollectionLevelList(hmzCollectionLevel);
                    if(hmzCollectionLevels !=null && hmzCollectionLevels.size() > 0){
                        stu.setCollectionLevel(String.valueOf(hmzCollectionLevels.get(0).getId()));
                    }
                }
                //藏品来源
                String collectionSource = stu.getCollectionSource();
                if(!"".equals(collectionSource) && null!=collectionSource){
                    HmzCollectionSource hmzCollectionSource = new HmzCollectionSource();
                    hmzCollectionSource.setCollectionSource(collectionSource);
                    List<HmzCollectionSource> hmzCollectionSources = hmzCollectionSourceService.selectHmzCollectionSourceList(hmzCollectionSource);
                    if(hmzCollectionSources !=null && hmzCollectionSources.size() > 0){
                        stu.setCollectionSource(String.valueOf(hmzCollectionSources.get(0).getId()));
                    }
                }
                int i = hmzProductMapper.insertHmzProduct(stu);
            } catch (Exception e) {
                failureNum++;
//                list.add(stu.getCornet());
                list.add(stu.getProductName());
                failureMsg.insert(0, list);
                throw new RuntimeException(e);
            }
//            try
//            {
//                // 验证是否存在这个用户
//                List<WmsInventory> wmsInventories = wmsInventoryMapper.selectWmsInventoryList(new WmsInventory().setRfidCode(stu.getRfidCode()));
//                if (StringUtils.isNull(u))
//                {
//                    BeanValidators.validateWithException(validator, stu);
//                    stu.setCreateBy(operName);
//                    this.insertStudentBase(stu);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、学号 " + stu.getStudentNumber() + " 导入成功");
//                }
//                else if (isUpdateSupport)
//                {
//                    BeanValidators.validateWithException(validator, stu);
//                    stu.setUpdateBy(operName);
//                    this.updateStudentBase(stu);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、学号 " + stu.getStudentNumber() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、学号 " + stu.getStudentNumber() + " 已存在");
//                }
//            }
//            catch (Exception e)
//            {
//                failureNum++;
//                String msg = "<br/>" + failureNum + "、学号 " + stu.getStudentNumber() + " 导入失败：";
//                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
//            }
        }
        if (failureNum > 0)
        {
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条");
        }
        return successMsg.toString();

    }
}
